package com.kl.component.spring.filter;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 通用拦截器
 *
 * <p>存储页面公用数据</p>
 *
 * @author xr_zjb
 * @date 2017/2/11 15:56
 *
 */
public class CommonIntercept implements HandlerInterceptor {


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取项目绝对路径，保证项目路径一致性
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int port = request.getServerPort();
        String path = request.getContextPath();
        String basePath = scheme + "://" + serverName;
        if(port != 80){
            basePath = basePath + ":" + port;
        }
        if(!StringUtils.isEmpty(path)){basePath = basePath + "/" + path;

        }
        request.setAttribute("ctx", basePath);
        response.setHeader("Origin", basePath);
        response.setHeader("Origin", basePath);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", basePath);
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
